import { defineStore } from 'pinia';
import { getLogin, getInfo } from '../api/user/index';
import { ILoginForm, ILoginCallback } from '../api/user/type';
import router from '@/router';
import type { RouteRecordRaw } from 'vue-router';
import { ElNotification } from 'element-plus';
//常量路由
// import { constantRoute } from '@/router/routes';

interface IState {
  token: string | null;
  menuRoutes: RouteRecordRaw[] | null;
  asideWidth: string;
  userName: string;
  userUrl: string;
}
/**
 * 换个插件，不要用pinia-plugin-persist（我觉得这个插件很坑哈），
 * 使用pinia-plugin-persistedstate，这个的官网配置查看
 * https://prazdevs.github.io/pinia-plugin-persistedstate/zh/gui...
 * 使用这个插件，你定义defineStore时会自动给你添加额外的类型定义，就不会报错了
 */
export const useUserStore = defineStore('user', {
  state: (): IState => ({
    // count: 0
    token: localStorage.getItem('he_token'),
    //仓库存储生成菜单需要数组(路由)
    menuRoutes: JSON.parse(localStorage.getItem('he_menuRoutes')) || null,
    //菜单宽度
    asideWidth: '250px',
    userName: '',
    userUrl: ''
  }),
  getters: {
    // double: state => state.count * 2
  },
  actions: {
    // increment() {
    //   this.count++;
    // }
    getLoginAct(data: ILoginForm) {
      getLogin(data).then(
        async (res: ILoginCallback) => {
          if (res.msg === 'ok') {
            this.token = res.data.token;
            localStorage.setItem('he_token', res.data.token);
            await getInfo().then(
              (res: any) => {
                if (res.msg === 'ok') {
                  this.menuRoutes = res.data.menus;

                  localStorage.setItem('he_menuRoutes', JSON.stringify(res.data.menus));
                  router.push('/');
                  ElNotification({ type: 'success', message: '登录成功' });
                }
              },
              err => {
                console.log(err);
              }
            );
          }
        },
        err => {
          console.log(err);
        }
      );
    },
    getInfoAct() {
      return new Promise((resolve, reject) => {
        getInfo().then(
          (res: any) => {
            if (res.msg === 'ok') {
              this.menuRoutes = res.data.menus;
              console.log(res.data.username);
              this.userName = res.data.username;
              this.userUrl = res.data.avatar;
              localStorage.setItem('he_menuRoutes', JSON.stringify(res.data.menus));
              resolve(res.data.menus);
            }
          },
          err => {
            console.log(err);
          }
        );
      });
    },
    clearUserInfo() {
      this.token = '';
      localStorage.removeItem('he_token');
    }
  },
  //使用持久化
  persist: true
});
